<?php

namespace app\consultant_module\controller;

use \app\common\controller\Base;
use \think\Validate;
use \think\Config;

class Index extends Base
{
    /*
     * 继承父类的_initialize()，并且添加上新的定义
     */
    public function _initialize()
    {
        parent::_initialize();
//      $this->Consultant = model('Consultant');
    }


    public function index()
    {
        $this->redirect("consultant_module/index/show_list");//页面的跳转
    }

    /*
     * 咨询者信息查询
     * 用param获取页面传过来的值
     * 如果SQL语句过多时要用数组装起
     * paginate()分页
     * 把分页数据赋值给模板变量list
     */
    public function show_list()
    {
        $name = input("?name") ? input("name") : "";//搜索名字
        $phone = input("?phone") ? input("phone") : "";//搜索电话号码
        $date = input("?search_date") ? input("search_date") : "";//搜索日期
        $contact_state = input("?contact_state") ? input("contact_state") : 999;//搜索的联系状态
        $visit_state = input("?visit_state") ? input("visit_state") : 999;//搜索的上门情况
        $intention_id = input("?intention_id") ? input("intention_id") : 999;//搜索的意向情况
        $now_consultant = input("?now_consultant") ? input("now_consultant") : "";//当前的咨询者id
        $is_record = input("?is_record") ? input("is_record") : false;//记录的咨询者名称
        $term['c.name'] = ['like', "%" . $name . "%"];
        $term['is_student'] = "0";
        $start_time = 0;
        $end_time = 9999999999;
        if (session("permissionsgroup_id") != 1) {
            $term['staff_id'] = session("user_id");
        }
        if ($phone) {
            $term['c.phone'] = $phone;
        }
        if ($contact_state != 999) {
            $term['c.contact_state'] = $contact_state;
            $contact_state = $contact_state == 0 ? 2 : $contact_state;
        }
        if ($visit_state != 999) {
            $term['c.visit_state'] = $visit_state;
            $visit_state = $visit_state == 0 ? 2 : $visit_state;
        }
        if ($intention_id != 999) {
            $term['c.intention_id'] = $intention_id;
        }
        if ($date) {
            $start_time = strtotime($date);
            $end_time = $start_time + 86399;
        }
        /*分页条件查询(配合get使用)*/
        $pageParam = ['query' => []];
        $pageParam['query']['name'] = $name;
        $pageParam['query']['phone'] = $phone;
        $pageParam['query']['contact_state'] = $contact_state;
        $pageParam['query']['visit_state'] = $visit_state;
        $pageParam['query']['intention_id'] = $intention_id;
        $pageParam['query']['search_date'] = $date;

        $list = db("consultant")
            ->alias('c')
            ->join('staff s', 's.id = c.staff_id', 'LEFT')
            ->join('consultant_intention ci', 'ci.id = c.intention_id', 'LEFT')
            ->where($term)
            ->where('c.first_contact_date', 'between', '' . $start_time . ',' . $end_time . '')
            ->field('c.id,c.name,c.phone,s.name as s_name,c.visit_state,c.contact_state,ci.type,c.first_contact_date')
            ->order('id', "desc")
            ->paginate(30, false, $pageParam);
        $record = db('consultant_record')->where(['consultant_id' => $now_consultant, 'staff_id' => session("user_id")])->order('id', "desc")->select();

        $intention_list = db("consultant_intention")->select();
        if ($is_record) {
            return json([
                'status' => 1
                , 'msg' => "查询成功"
                , 'data' => $record
                , 'now_consultant' => $now_consultant
                , 'intention_list' => $intention_list
            ]);
        } else {
            $this->assign([
                'list' => $list
                , 'name' => $name
                , 'now_consultant' => $now_consultant
                , 'intention_list' => $intention_list
                , 'phone' => $phone
                , 'contact_state' => $contact_state
                , 'visit_state' => $visit_state
                , 'intention_id' => $intention_id
                , 'date' => $date
            ]);
            return view();
        }
    }

    /*
     * 根据ID拿取咨询者信息
     */
    public function get_consultant_info($now_consultant = "")
    {
        $res = db("consultant")
            ->alias('c')
            ->join('education edu', 'edu.id = c.education_id', 'LEFT')
            ->join('position pos', 'pos.id = c.position', 'LEFT')
            ->join('consultant_intention ci', 'ci.id = c.intention_id', 'LEFT')
            ->join('consultant_channel cc', 'cc.id = c.channel_id', 'LEFT')
            ->where('c.id', $now_consultant)
            ->field('c.id,c.name,c.phone,c.sex,edu.grade,c.school,c.wechat,c.qq,pos.name as position,c.major,c.visit_state,ci.type as intention,cc.type as channel,c.contact_state')
            ->select();
        return $res;
    }

    /*
     * 根据ID修改咨询者信息或添加咨询者信息的页面展示
     * view()直接展示页面不用经过渲染,注意与$view->fetch()区别(渲染模板输出)
     */
    public function show_add_edit($now_consultant = "")
    {
        $education_list = db("education")->select();
        $intention_list = db("consultant_intention")->select();
        $channel_list = db("consultant_channel")->select();
        $position_list = db("position")->where('status', 1)->select();
        $this->assign([
            "education_list" => $education_list
            , "intention_list" => $intention_list
            , "channel_list" => $channel_list
            , "position_list" => $position_list
        ]);
        if (!empty($now_consultant)) {
            $consultant = db('consultant')->where('id', $now_consultant)->find();
            $this->assign(['consultant' => $consultant, 'is_add' => false]);
            return view("index/show_edit");
        } else {
            $this->assign('is_add', true);
            return view("index/show_add");
        }
    }

    /*
     * 检查是否重复
     */
    public function check_info()
    {
        $phone = trim(input("now_add_phone"));
        $res = db("consultant")
            ->alias('c')
            ->join('staff s', 's.id = c.staff_id', 'LEFT')
            ->where(['c.phone' => $phone])
            ->field("s.name as staff_name,c.name")
            ->select();
        return $res;
    }

    /*
     * 根据ID修改咨询者信息或添加咨询者信息
     * save(),success(),error()
     */
    public function commit_add_edit()
    {
        $id = input("id");
        $name = trim(input("name"));
        $phone = trim(input("phone"));
        $sex = trim(input("sex"));
        $education_id = trim(input("education_id"));
        $school = trim(input("school"));
        $wechat = trim(input("wechat"));
        $qq = trim(input("qq"));
        $position = trim(input("position"));
        $major = trim(input("major"));
        $visit_state = trim(input("visit_state"));
        $intention_id = trim(input("intention_id"));
        $channel_id = trim(input("channel_id"));
        $contact_state = trim(input("contact_state"));
        $staff_id = session("user_id");
        $first_contact_date = time();
        $is_wechat = input("is_wechat") == "true" ? "1" : "0";
        $record_content = trim(input("record_content"));
        $time = date('Y-m-d h:i:s', time());//时间
        $time_s = date('Y-m-d');//时间
        $msg = "";
        $res = "";
        if (empty($id)) {
            $res = db("consultant")
                ->alias('c')
                ->join('staff s', 's.id = c.staff_id', 'LEFT')
                ->where(['c.name' => $name, 'c.phone' => $phone])
                ->value('s.name');
        }
        if (empty($name) == 1) {
            $msg = '姓名不能为空';
        } else if (empty($phone) == 1) {
            $msg = '手机号码不能为空';
        } else if ($res) {
            $msg = '咨询者已存在,请重新输入手机号码';
        } else if (is_phone($phone) == 0) {
            $msg = '手机号码格式错误';
        } else if (empty($phone) == 1 && is_num($qq) == 0) {
            $msg = 'QQ号码格式错误';
        }
        if ($msg != "") {
            alert($msg, "error");
        }
        if (!empty($id)) {
            $old_data = db("consultant")
                ->where('id', $id)
                ->field('channel_id,visit_state,intention_id,contact_state')
                ->find();
            $visit_state = $old_data['visit_state'];
            $intention_id = $old_data['intention_id'];
            $channel_id = $old_data['channel_id'];
            $contact_state = $old_data['contact_state'];
        }
        $info = [
            'name' => $name
            , 'phone' => $phone
            , 'sex' => $sex
            , 'education_id' => $education_id
            , 'school' => $school
            , 'wechat' => $wechat
            , 'qq' => $qq
            , 'position' => $position
            , "major" => $major
            , "visit_state" => $visit_state
            , "intention_id" => $intention_id
            , "channel_id" => $channel_id
            , "contact_state" => $contact_state
            , "staff_id" => $staff_id
            , "first_contact_date" => $first_contact_date
            , 'is_wechat' => $is_wechat
        ];
        if (empty($id)) {
            $consultant = model('consultant');
            $consultant->data($info);
            $consultant->save();
            $consultant_id = $consultant->id;
            $info = [
                "consultant_id" => $consultant_id
                , "staff_id" => $staff_id
                , "time" => $time
                , "content" => $record_content
            ];
            if (!empty($record_content)) {
                $res = db('consultant_record')->insert($info);
            }
            $have_number = db("staff_consultant_number")
                ->where(["staff_id" => session('user_id'), "date" => $time_s])
                ->find();
            if ($have_number != NULL) {
                $now_number = $have_number['number'] + 1;
                db('staff_consultant_number')->where('staff_id', session('user_id'))
                    ->update(['number' => $now_number]);
            } else {
                db('staff_consultant_number')
                    ->insert(['staff_id' => session('user_id'), 'date' => $time_s, 'number' => 1]);
            }
            if ($consultant_id) {
                alert("添加成功", "success", "show_list");
            } else {
                alert("添加失败", "error");
            }
        } else {
            $res = db('consultant')->where('id', $id)->update($info);
            if ($res) {
                alert("更新成功", "success", "/consultant_module/index/show_list");
            } else {
                alert("更新失败", "error");
            }
        }
    }

    /*
     * 展示咨询者记录
     */
    public function show_record()
    {
        $now_consultant = input("?now_consultant") ? input("now_consultant") : "";//当前的咨询者id
        $res = permission();//获取当前职员的权限
        if (in_array("consultant_module_show_record", $res[0])) {
            $conditions_record = ['c.consultant_id' => $now_consultant];
        } else {
            $conditions_record = ['s.id' => session("user_id"), 'c.consultant_id' => $now_consultant];
        }
        $intention_list = db("consultant_intention")->select();
        $consultant = db('consultant')->where('id', $now_consultant)->find();
        $record = db("consultant_record")
            ->alias('c')
            ->join('staff s', 's.id = c.staff_id', 'LEFT')
            ->where($conditions_record)
            ->order('c.id desc')
            ->select();
        $res = json([
            'status' => 1
            , 'msg' => "查询成功"
            , 'record' => $record
            , 'intention_list' => $intention_list
            , 'consultant_list' => $consultant
        ]);
        return $res;
    }

    /*
     * 添加咨询者记录
     */
    public function confirm_record()
    {
        $record_content = trim(input("record_content"));
        $visit_state = trim(input("visit_state"));
        $intention_id = trim(input("intention_id"));
        $contact_state = trim(input("contact_state"));
        $now_consultant = input("now_consultant");//当前的咨询者id
        $time = date('Y-m-d', time());//时间
        $staff_id = session("user_id");
        $data = [
            "visit_state" => $visit_state
            , "contact_state" => $contact_state
            , "intention_id" => $intention_id
        ];
        $result = db('consultant')->where('id', $now_consultant)->update($data);
        $info = [
            "consultant_id" => $now_consultant
            , "staff_id" => $staff_id
            , "time" => $time
            , "content" => $record_content
        ];
        $res = db('consultant_record')->insert($info);
        if ($res) {
            return json([
                'status' => 1,
                'msg' => "添加成功"
            ]);
        } else {
            return json([
                'status' => 0,
                'msg' => "添加失败"
            ]);
        }
    }

    //导数据
    public function crm_data()
    {
        set_time_limit(0);
        $list = db("consultant_copy")
            ->alias('cc')
            ->join('consul_stu_phones csp', 'csp.consultant_id = cc.consultant_id', 'LEFT')
            ->join('consul_stu_qq csq', 'csq.consultant_id = cc.consultant_id', 'LEFT')
//        ->limit(0,4000)
            ->field('cc.consultant_name,csp.phone_number,csq.qq_number,cc.consultant_set_view,cc.consultant_channel_id,cc.consultant_firsttime,cc.employee_id,cc.consultant_education')
            ->select();
        $cc = db('consultant');
        foreach ($list as $v) {
            unset($info_consultant);
            $now_name = $v['consultant_name'];
            $now_phone = $v['phone_number'];
            $now_qq = $v['qq_number'];
            $now_view = $v['consultant_set_view'];
            $now_staff = $v['employee_id'];
            $now_first = $v['consultant_firsttime'];
            switch ($v['consultant_channel_id']) {
                case 4:
                    $now_channel = 3;
                    break;
                case 10:
                    $now_channel = 2;
                    break;
                default:
                    $now_channel = 1;
            };


            switch ($v['consultant_education']) {
                case "本科":
                    $now_education = 3;
                    break;
                case "大专":
                    $now_education = 4;
                    break;
                default:
                    $now_education = 5;
            };

            $info_consultant = [
                'name' => $now_name
                , 'phone' => $now_phone
                , 'qq' => $now_qq
                , 'staff_id' => $now_staff
                , 'visit_state' => $now_view
                , 'first_contact_date' => $now_first
                , 'channel_id' => $now_channel
                , 'education_id' => $now_education
                , 'intention_id' => 1
                , 'contact_state' => 0
            ];
            $cc->insert($info_consultant);

        }
    }

    public function add_record()
    {
        set_time_limit(0);
        $record_list = db('consultant_record_copy')
            ->alias('crc')
            ->join('consultant_copy cc', 'cc.consultant_id = crc.consultant_id', 'LEFT')
            ->field('crc.consultant_id,crc.consultant_record_desc,crc.consultant_record_time,cc.employee_id')->select();
        $rec = db('consultant_record');
        foreach ($record_list as $v) {
            $consultant_id = $v['consultant_id'];
            $time = date("Y-m-d", $v['consultant_record_time']);
            $content = $v['consultant_record_desc'];
            $staff_id = $v['employee_id'];
            $info_consultant = [
                'consultant_id' => $consultant_id
                , 'staff_id' => $staff_id
                , 'time' => $time
                , 'content' => $content
            ];
            $rec->insert($info_consultant);
        }

    }

    public function crm_record()
    {
        set_time_limit(0);
        $record_list = db('consultant_copy')
            ->alias('cc')
            ->join('consultant_record cr', 'cr.consultant_id = cc.consultant_id', 'RIGHT')->join('consultant c', 'c.name = cc.consultant_name', 'LEFT')
            ->field('cr.consultant_id,c.id')
            ->select();

        $db = db('consultant_record');
        foreach ($record_list as $v) {
            $db->where('consultant_id', $v['consultant_id'])
                ->update(['consultant_id' => $v['id']]);
        }
    }

}
